import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;

import momo.app.util.FileOutput;
import momo.app.util.IntByteConvert;

public class EchoClient
{
	private static String getTextContents(String filename)
	{
		File f = new File(filename);
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader in = new BufferedReader(new FileReader(f));
			String line = "";
			String lineSep = System.getProperty("line.separator");
			while( (line=in.readLine()) != null )
			{
				buffer.append(line);
				buffer.append(lineSep);
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
	public static void main(String args[])
	{
		final String match = getTextContents("./trial_2.txt");
		try {
			
			Socket client = new Socket("155.69.144.148", 1111);
			
			BufferedInputStream in = new BufferedInputStream(client.getInputStream());
			int bufferLimit = client.getReceiveBufferSize();
			
			while ( true )
			{
				ByteBuffer byteFileSize = ByteBuffer.allocate(4);
				for (int bytecount = 0; bytecount < 4; bytecount++) {
					int byteRead = in.read();
					if (byteRead == -1)
						throw new RuntimeException("header malformed: EOF while reading first 4 bytes");
					else
						byteFileSize.put((byte) byteRead);
				}
				byteFileSize.rewind();
				int expectedMsgSize = byteFileSize.getInt();
				int remaining = expectedMsgSize;
				ByteBuffer msg = ByteBuffer.allocate(expectedMsgSize);
				
//				System.out.println("Expected File Size: " + expectedFileSize);
				
				while ( remaining > 0 )
				{
					int chunkSize = (remaining > bufferLimit)? bufferLimit:remaining;
					
//					System.out.println("Remainig: " + remaining);
					
					byte[] chunkBuffer = new byte[chunkSize];
					int bytesRead = in.read(chunkBuffer);
					if (bytesRead == -1)
						throw new RuntimeException("body malformed: EOF while reading data; expecting "+remaining+" bytes more");
	
					byte[] trimmedChunk = Arrays.copyOf(chunkBuffer, bytesRead);
					
					msg.put(trimmedChunk);
					
					remaining -= bytesRead;
					
//					strBuffer.append( (char)in.read() );
//					rcv++;
				}
				// FIXME: do the conversion with UTF8
				String dataRcved = new String(msg.array());
				if ( !dataRcved.equals(match) )
				{
					System.out.println("does not match");
					FileOutput.getInstance().logToFile("A_no_match.txt", dataRcved+"\n");
					System.exit(0);
				}
			}
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
